package easy.netty.net.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author cengy
 */
public class Acceptor
        extends AbsIoService
        implements IoService {

    private static final
    Logger logger = LoggerFactory.getLogger(Acceptor.class);

    protected ServerBootstrap bootstrap;
    protected EventLoopGroup bossGroup;
    protected EventLoopGroup workerGroup;

    public Acceptor(Endpoint endpoint) {
        super(endpoint);
    }

    @Override
    public void open() {

        final IoConf netConf = endpoint.getIoConf();
        try {
            if (null == netConf) {
                throw new RuntimeException("netConf is null");
            }

            bootstrap = new ServerBootstrap();
            bossGroup = new NioEventLoopGroup(netConf.getBossThreadNum());

            workerGroup = new NioEventLoopGroup(netConf.getWorkerThreadNum());

            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(endpoint);

            Map<String, Object> options = new HashMap(netConf.getOptions());
            Object option = options.remove(ChannelOption.SO_BACKLOG.name().toLowerCase());
            bootstrap.option(ChannelOption.SO_BACKLOG,
                    (null == option || !(option instanceof Integer)) ? 1024 : Integer.valueOf(options.toString()));

            boolean tcpNoDelayOption = false;
            boolean soKeepAliveOption = false;

            for (Map.Entry<String, Object> optionSet : options.entrySet()) {
                ChannelOption op = ChannelOption.valueOf(optionSet.getKey().toUpperCase());
                if (null == op) continue;
                bootstrap.childOption(op, optionSet.getValue());
                if (op == ChannelOption.TCP_NODELAY) {
                    tcpNoDelayOption = true;
                }

                if (op == ChannelOption.SO_KEEPALIVE) {
                    soKeepAliveOption = true;
                }
            }

            if (!tcpNoDelayOption)
                bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

            if (!soKeepAliveOption)
                bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);


            ChannelFuture future =
                    bootstrap.bind(netConf.getIp(),
                            netConf.getPort()).sync();

            if (future.isSuccess()) {
                logger.info("the server {}:{} start successfully", netConf.getIp(),
                        netConf.getPort());
            }

        } catch (Exception e) {
            if (null != netConf) {
                logger.error("the server {}:{} start failure",
                        netConf.getIp(),
                        netConf.getPort(), e);
            }
            close();
        }
    }

    @Override
    public void close() {
        try {

            if (null != bossGroup)
                bossGroup.shutdownGracefully().sync();

            if (null != workerGroup)
                workerGroup.shutdownGracefully().sync();

        } catch (Exception e) {
            IoConf netConf = endpoint.getIoConf();
            if (null != netConf) {
                logger.error("the server {}:{} caught exception when close",
                        netConf.getIp(), netConf.getPort(), e);
            }
        }
    }
}
